package com.liu.student.controller;

import com.liu.student.entity.Student;
import com.liu.student.entity.Course;
import com.liu.student.entity.Enrollment;
import com.liu.student.service.StudentService;
import com.liu.student.service.CourseService;
import com.liu.student.service.EnrollmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 学生控制器
 */
@Controller
@RequestMapping("/student")
@PreAuthorize("hasAnyRole('STUDENT', 'ADMIN')")
public class StudentController {

    @Autowired
    private StudentService studentService;

    @Autowired
    private CourseService courseService;

    @Autowired
    private EnrollmentService enrollmentService;

    @GetMapping("/dashboard")
    public String dashboard(Model model) {
        // 获取当前登录学生的信息
        Student currentStudent = getCurrentStudent();
        if (currentStudent != null) {
            model.addAttribute("student", currentStudent);
            
            // 获取已选课程数量
            List<Enrollment> enrollments = enrollmentService.findByStudentId(currentStudent.getId());
            model.addAttribute("enrollmentCount", enrollments.size());
        }
        return "student/dashboard";
    }

    @GetMapping("/profile")
    public String profile(Model model) {
        Student currentStudent = getCurrentStudent();
        model.addAttribute("student", currentStudent);
        return "student/profile";
    }

    @PostMapping("/profile/update")
    public String updateProfile(@ModelAttribute Student student) {
        Student currentStudent = getCurrentStudent();
        if (currentStudent != null) {
            student.setId(currentStudent.getId());
            student.setUserId(currentStudent.getUserId());
            student.setStudentNumber(currentStudent.getStudentNumber()); // 学号不可修改
            studentService.update(student);
        }
        return "redirect:/student/profile";
    }

    @GetMapping("/courses")
    public String availableCourses(Model model) {
        List<Course> courses = courseService.findAvailableCourses();
        model.addAttribute("courses", courses);
        return "student/courses";
    }

    @GetMapping("/my-courses")
    public String myCourses(Model model) {
        Student currentStudent = getCurrentStudent();
        if (currentStudent != null) {
            List<Enrollment> enrollments = enrollmentService.findByStudentId(currentStudent.getId());
            model.addAttribute("enrollments", enrollments);
        }
        return "student/my-courses";
    }

    @PostMapping("/enroll/{courseId}")
    public String enrollCourse(@PathVariable Long courseId) {
        Student currentStudent = getCurrentStudent();
        if (currentStudent != null) {
            try {
                enrollmentService.enrollCourse(currentStudent.getId(), courseId);
                return "redirect:/student/my-courses?success=enrolled";
            } catch (Exception e) {
                return "redirect:/student/courses?error=" + e.getMessage();
            }
        }
        return "redirect:/student/courses";
    }

    @PostMapping("/drop/{courseId}")
    public String dropCourse(@PathVariable Long courseId) {
        Student currentStudent = getCurrentStudent();
        if (currentStudent != null) {
            try {
                enrollmentService.dropCourse(currentStudent.getId(), courseId);
                return "redirect:/student/my-courses?success=dropped";
            } catch (Exception e) {
                return "redirect:/student/my-courses?error=" + e.getMessage();
            }
        }
        return "redirect:/student/my-courses";
    }

    @GetMapping("/schedule")
    public String schedule(Model model) {
        Student currentStudent = getCurrentStudent();
        if (currentStudent != null) {
            List<Enrollment> enrollments = enrollmentService.findByStudentId(currentStudent.getId());
            model.addAttribute("enrollments", enrollments);
        }
        return "student/schedule";
    }

    private Student getCurrentStudent() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated()) {
            String username = authentication.getName();
            return studentService.findByUsername(username);
        }
        return null;
    }
}